package com.andaily.web.controller.mobile.thing;

import com.andaily.domain.dto.thing.ThingDto;
import com.andaily.domain.dto.thing.ThingMonitoringDto;
import com.andaily.domain.thing.ThingPriority;
import com.andaily.domain.thing.ThingStatus;
import com.andaily.service.ThingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/thing/monitoring")
public class ThingMonitoringController {

    @Autowired
    private ThingService thingService;


    @RequestMapping("overview")
    public String overview(ThingMonitoringDto thingMonitoringDto, Model model) throws Exception {
        thingMonitoringDto = thingService.loadThingMonitoringDto(thingMonitoringDto);
        model.addAttribute("thingMonitoringDto", thingMonitoringDto);
        return "thing/thing_monitoring_overview";
    }

    @RequestMapping("overview/more")
    public String more(ThingMonitoringDto thingMonitoringDto, Model model) throws Exception {
        thingMonitoringDto = thingService.loadThingMonitoringDto(thingMonitoringDto);
        model.addAttribute("thingMonitoringDto", thingMonitoringDto);
        return "thing/thing_monitoring_overview_more";
    }

    @RequestMapping("action/{guid}")
    public String action(@PathVariable() String guid, Model model) throws Exception {
        ThingDto thingDto = thingService.loadExistThingDto(guid);
        model.addAttribute("thingDto", thingDto);
        model.addAttribute("hasHighThings", hasHighThings(thingDto));
        return "thing/thing_monitoring_action";
    }

    @RequestMapping("changestatus/{guid}/{status}")
    public String changeStatus(@PathVariable("guid") String guid, @PathVariable("status") ThingStatus status) {
        thingService.changeThingStatus(guid, status);
        return "redirect:../../overview?result=true";
    }

    private boolean hasHighThings(ThingDto thingDto) {
        boolean hasHighThings = thingService.hasHighThings();
        return hasHighThings
                && ThingStatus.CREATED.equals(thingDto.getStatus())
                && !(ThingPriority.HIGH.equals(thingDto.getPriority()) || ThingPriority.HIGHER.equals(thingDto.getPriority()));
    }

}
